import axios from 'axios';
import Qs from 'qs'

axios.defaults.timeout = 15000;
axios.defaults.baseURL ='';
const urlShort = 'http://134.175.34.153:3000'
// const urlShort = 'http://127.0.0.1:3000'

//http request 拦截器
axios.interceptors.request.use(
  config => {
    // const token = getCookie('名称');注意使用的时候需要引入cookie方法，推荐js-cookie
    // 这里已经用qs模块进行了参数序列化，没有必要再用JSON.stringify
    // config.data = JSON.stringify(config.data);
    config.headers = {
      'Content-Type':'application/x-www-form-urlencoded'
    }
    // if(token){
    //   config.params = {'token':token}
    // }
    return config;
  },
  error => {
    return Promise.reject(err);
  }
);


//http response 拦截器
axios.interceptors.response.use(
  response => {
    if(response.data.errCode == 2){
      router.push({
        path:"/login",
        querry:{redirect:router.currentRoute.fullPath}//从哪个页面跳转
      })
    }
    return response;
  },
  error => {
    return Promise.reject(error)
  }
)


/**
 * 封装get方法
 * @param url
 * @param data
 * @returns {Promise}
 */

export function fetch(url, params={}){
  let urlLong = urlShort + url
  return new Promise((resolve,reject) => {
    axios.get(urlLong,{
      params:params
    })
    .then(response => {
      resolve(response.data);
    })
    .catch(err => {
      reject(err)
    })
  })
}


/**
 * 封装post请求
 * @param url
 * @param data
 * @returns {Promise}
 */

 export function post(url, data = {}){
  let urlLong = urlShort + url
  let _data = Qs.stringify(data)
  return new Promise((resolve,reject) => {
      axios.post(urlLong,_data)
      .then(response => {
        resolve(response.data);
      },err => {
        reject(err)
      })
  })
 }

 /**
 * 封装patch请求
 * @param url
 * @param data
 * @returns {Promise}
 */

export function patch(url, data = {}){
  let urlLong = urlShort + url

  return new Promise((resolve,reject) => {
    axios.patch(ururlLongl,data)
         .then(response => {
           resolve(response.data);
         },err => {
           reject(err)
         })
  })
}

 /**
 * 封装put请求
 * @param url
 * @param data
 * @returns {Promise}
 */

export function put(url, data = {}){
  let urlLong = urlShort + url
  return new Promise((resolve,reject) => {
    axios.put(urlLong,data)
         .then(response => {
           resolve(response.data);
         },err => {
           reject(err)
         })
  })
}
